package com.wd.jetpack.ui.main

import android.Manifest
import android.content.pm.PackageManager
import android.view.View
import androidx.core.app.ActivityCompat
import com.google.gson.Gson
import com.wd.jetpack.R
import com.wd.jetpack.base.BaseActivity
import com.wd.jetpack.databinding.ActivityDemoRoomBinding
import com.wd.jetpack.model.ArticleBean
import com.wd.jetpack.model.data.AppDatabase
import com.wd.jetpack.ui.viewmodel.DemoRoomViewModel
import com.wd.jetpack.util.Logger

/**
 * NA<BR>
 *
 * @author w4425
 * @version [V5.9.3, 2021/6/17]
 * @since V5.9.3
 */
class DemoRoomActivity : BaseActivity<ActivityDemoRoomBinding>() {
    private val mVm: DemoRoomViewModel by lazy { DemoRoomViewModel() }

    private val database: AppDatabase by lazy {
        AppDatabase.getInstance(this)
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_demo_room
    }

    override fun initView() {
        mBinding.vm = mVm
    }

    override fun initData() {
        verifyPermissions()
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.btn_add -> {
                doAdd()
            }
            R.id.btn_delete -> {
                doDelete()
            }
            R.id.btn_update -> {
                doUpdate()
            }
            R.id.btn_query -> {
                doQuery()
            }
        }
    }

    private fun doAdd() {
        database.articleDao().insert(ArticleBean())
    }

    private fun doDelete() {
        //查询第一条数据
        val data = database.articleDao().findFirst()
        data?.let {
            database.articleDao().delete(it)
        }
    }

    private fun doUpdate() {
        val data = database.articleDao().findFirst()
        data?.let {
            val updateData = data.apply {
                author_name = "作者"
            }
            database.articleDao().update(updateData)
        }
    }

    private fun doQuery() {
        val allData = database.articleDao().findAll()
        Logger.e(Gson().toJson(allData))
    }

    private fun verifyPermissions() {
        val read_permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
        val write_permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        if (read_permission != PackageManager.PERMISSION_GRANTED ||
                write_permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STREAM,
                    REQUEST_STREAM
            )
        }
    }

    companion object {
        private const val REQUEST_STREAM = 1
        private val PERMISSIONS_STREAM = arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS
        )
    }
}